package main

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"golang.org/x/sync/errgroup"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	eg, ctx := errgroup.WithContext(context.Background())

	// 信号传输
	signChan := make(chan os.Signal, 1)
	signal.Notify(signChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) // 三个退出信号
	defer close(signChan)

	// http server 的启动和关闭
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintln(resp, "Hello World!")
	})

	server := http.Server{
		Addr:    "8888",
		Handler: mux,
	}
	defer server.Close()

	eg.Go(func() error {
		return server.ListenAndServe()
	})

	eg.Go(func() error {
		select {
		case sign := <-signChan:
			fmt.Sprintf("收到退出信号%v", sign)
			return errors.New("sign quit")
		case <-ctx.Done():
			return ctx.Err()
		}
	})

	if err := eg.Wait(); err != nil {
		return
	}
}
